import axios from 'axios'

const DB_NAME = 'jnks-gov_online-model'
const DB_VERSION = 1 // Use a long long for this value (don't use a float)
const DB_STORE_NAME = 'gov_online_model_gltf'

// 加载数据库
function initDb() {
    if (!window.indexedDB) {
        console.log("Your browser doesn't support a stable version of IndexedDB.")
        return
    }

    let request = indexedDB.open(DB_NAME, DB_VERSION)

    return new Promise((resolve, reject) => {
        request.onerror = function () {
            console.log('error: create db error')
            reject()
        }
        request.onupgradeneeded = function (evt) {
            evt.currentTarget.result.createObjectStore(DB_STORE_NAME, { keyPath: 'ssn' })
        }
        request.onsuccess = function (evt) {
            console.log('onsuccess: create db success ')
            resolve(evt.target.result)
        }
    })
}

// 获取模型
async function getModel(url, id) {
    let db = await initDb()
    let getRequest = db.transaction([DB_STORE_NAME], 'readwrite').objectStore(DB_STORE_NAME).get(id)
    return new Promise((resolve, reject) => {
        getRequest.onsuccess = function (event) {
            let modelFile = event.target.result
            // 假如已经有缓存了 直接用缓存
            if (modelFile) {
                resolve(modelFile.blob)
            } else {
                // 假如没有缓存 请求新的模型存入
                inputModel(url, id)
                    .then(blob => {
                        resolve(blob)
                    })
                    .catch(() => {
                        reject()
                    })
            }
        }
        getRequest.onerror = function (event) {
            console.log('error', event)
            reject()
        }
    })
}

// 存入模型
async function inputModel(url, id) {
    let db = await initDb()
    let modelResult = await axios.get(url, {
        responseType: 'blob',
        onDownloadProgress: e => {
            if (id == 1) {
                window.dispatchEvent(
                    new CustomEvent('loadingProgress', {
                        detail: (e.loaded * 100 / e.total).toFixed(2)
                    })
                )
            }
        }
    })
    if (modelResult.status == 200) {
        let obj = {
            ssn: id
        }
        obj.blob = new Blob([modelResult.data])
        let inputRequest = db
            .transaction([DB_STORE_NAME], 'readwrite')
            .objectStore(DB_STORE_NAME)
            .add(obj)
        return new Promise((resolve, reject) => {
            inputRequest.onsuccess = function () {
                console.log('glb数据添加成功')
                resolve(obj.blob)
            }
            inputRequest.onerror = function (evt) {
                console.log('glb数据添加失败', evt)
                reject()
            }
        })
    }
}

export { getModel, inputModel }
